Component({
  data: {
    selected: 0,
    list: [
      {
        pagePath: "/pages/home/index",
        iconPath: "/images/icons/home_gray.png",
        selectedIconPath: "/images/icons/home.png",
        text: "首页"
      },
      {
        pagePath: "/pages/activity/index",
        iconPath: "/images/icons/activity_gray.png",
        selectedIconPath: "/images/icons/activity.png",
        text: "活动"
      },
      {
        pagePath: "/pages/shop/index",
        iconPath: "/images/icons/shop_gray.png",
        selectedIconPath: "/images/icons/shop.png",
        text: "商店"
      },
      {
        pagePath: "/pages/mine/index",
        iconPath: "/images/icons/mine_gray.png",
        selectedIconPath: "/images/icons/mine.png",
        text: "我的"
      }
    ]
  },

  attached() {
    // 组件初始化时设置当前页面索引
    this.setCurrentPageIndex()
  },

  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset
      const url = data.path
      const index = data.index

      // 如果点击的是当前页面，不做操作
      if (this.data.selected === index) {
        return
      }

      wx.switchTab({
        url: url,
        success: () => {
          this.setData({
            selected: index
          })
        },
        fail: (err) => {
          console.error('switchTab failed: ', err)
        }
      })
    },

    setCurrentPageIndex() {
      // 获取当前页面路径，设置对应的tab选中状态
      const pages = getCurrentPages()
      if (pages.length > 0) {
        const currentPage = pages[pages.length - 1]
        const currentRoute = `/${currentPage.route}`
        
        const index = this.data.list.findIndex(item => 
          item.pagePath === currentRoute || 
          item.pagePath === currentRoute.replace(/^\//, '')
        )
        
        if (index !== -1) {
          this.setData({
            selected: index
          })
        }
      }
    },

    // 提供给外部调用的方法，用于更新选中状态
    updateSelected(index) {
      if (index >= 0 && index < this.data.list.length) {
        this.setData({
          selected: index
        })
      }
    }
  }
})